package com.star.spring.netty.util;

public class HexUtils {
    
    /**
     * Convert hex string to byte array
     * @param hexString the hex string
     * @return byte array
     */
    public static byte[] hexToBytes(String hexString) {
        if (hexString == null || hexString.isEmpty()) {
            return new byte[0];
        }
        
        // Remove spaces and convert to uppercase
        hexString = hexString.replaceAll(" ", "").toUpperCase();
        
        int length = hexString.length();
        byte[] bytes = new byte[length / 2];
        
        for (int i = 0; i < length; i += 2) {
            bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i + 1), 16));
        }
        
        return bytes;
    }
    
    /**
     * Convert byte array to hex string
     * @param bytes the byte array
     * @return hex string
     */
    public static String bytesToHex(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return "";
        }
        
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        
        return hexString.toString().toUpperCase();
    }
    
    /**
     * Parse hex data packet
     * @param hexData the hex data string
     * @return parsed data as string
     */
    public static String parseHexPacket(String hexData) {
        if (hexData == null || hexData.isEmpty()) {
            return "";
        }
        
        // Remove spaces for consistent parsing
        hexData = hexData.replaceAll(" ", "").toUpperCase();
        
        // Basic parsing - in a real implementation, you would parse according to your protocol
        StringBuilder parsedData = new StringBuilder();
        parsedData.append("Packet Length: ").append(hexData.length() / 2).append(" bytes\n");
        
        // Example: parse first few bytes as header
        if (hexData.length() >= 4) {
            parsedData.append("Header: ").append(hexData.substring(0, 4)).append("\n");
        }
        
        // Example: parse remaining bytes as payload
        if (hexData.length() > 4) {
            parsedData.append("Payload: ").append(hexData.substring(4)).append("\n");
        }
        
        return parsedData.toString();
    }
}